﻿using UnityEngine;
using System.Collections;

public class TowerScript : MonoBehaviour {

	public GameObject currentTarget = null;
	RotateLookTarget rotateLookTarget = null;

	float deltaTime = 0.0f;
	public float fireStateUpdateTime = 1.2f;
	public float fireActiveTime = 0.5f;
	MuzzleFlashAnimate[] muzzleFlashs = null;

	public float attackPower = 1.0f;

	void Start(){
		rotateLookTarget = GetComponentInChildren<RotateLookTarget> ();
		muzzleFlashs = GetComponentsInChildren<MuzzleFlashAnimate> ();
		foreach (MuzzleFlashAnimate muzzleFlash in muzzleFlashs) {
			muzzleFlash.InitMuzzleFlash();
		}
	}

	void OnTriggerEnter(Collider other) 
	{
		if (currentTarget == null) currentTarget = other.gameObject;
	}

	void Update(){
		if (currentTarget == null) return;
		rotateLookTarget.RotateToTarget (currentTarget.transform);
		deltaTime += Time.deltaTime;

		if (deltaTime > fireStateUpdateTime) {
			deltaTime = -fireActiveTime;
			FireProcess();
		}

	}

	void FireProcess(){
		foreach (MuzzleFlashAnimate muzzleFlashAnimate in muzzleFlashs) {
			muzzleFlashAnimate.ActiveMuzzleFlash(fireActiveTime);
		}
		EnemyState enemyState = currentTarget.GetComponent<EnemyState> ();
		enemyState.Damage(transform,fireActiveTime,attackPower);
	}
}
